package com.nidu.demo.menu.executor.command;

import com.alibaba.cola.dto.SingleResponse;
import com.nidu.demo.common.enums.MenuTypeEnum;
import com.nidu.demo.menu.ability.MenuDomainService;
import com.nidu.demo.menu.convertor.MenuConvertor;
import com.nidu.demo.menu.dto.MenuCO;
import com.nidu.demo.menu.dto.MenuUpdateCmd;
import com.nidu.demo.menu.gateway.MenuGateway;
import com.nidu.demo.menu.model.Menu;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 菜单更新命令执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class MenuUpdateCmdExe {

    private final MenuGateway gateway;

    private final MenuDomainService domainService;

    private final MenuConvertor convertor;

    public SingleResponse<MenuCO> execute(MenuUpdateCmd cmd) {
        // 1. 转换为领域对象
        MenuTypeEnum menuType = MenuTypeEnum.of(cmd.getMenuType());
        Menu menu = null;
        switch (Objects.requireNonNull(menuType)){
            case BUTTON:
                menu = Menu.updatePermission(cmd.getId(), cmd.getMenuName(), cmd.getPermission(), cmd.getParentId(), cmd.getSortOrder());
                break;
            case DIRECTORY:
            case MENU:
                menu = Menu.update(cmd.getId(), cmd.getMenuName(), cmd.getMenuType(), cmd.getParentId(), cmd.getIcon(), cmd.getIconType(),
                        cmd.getRouteName(), cmd.getRoutePath(), cmd.getComponent(), cmd.getI18nKey(), cmd.getHref(), cmd.getSortOrder());
                break;
            default:
                break;
        }

        // 2. 检查名称是否重复
        domainService.validateDuplicate(menu.getMenuName(), menu.getId());
        // 3. 检查父菜单是否启用
        domainService.validateParentId(menu.getParentId());

        // 4. 调用网关保存
        Menu save = gateway.update(menu);

        // 5. 转换为DTO返回
        MenuCO menuCO = convertor.toClientObject(save);

        return SingleResponse.of(menuCO);
    }
} 